package com.ecloud.gardensterminal.mqtt;

import com.ecloud.gardensterminal.mqtt.constant.MqttMessageArrivedCall;
import com.ecloud.gardensterminal.mqtt.constant.MqttInitializer;
import lombok.Data;
import org.eclipse.paho.mqttv5.client.MqttCallback;
import org.eclipse.paho.mqttv5.client.MqttClient;
import org.eclipse.paho.mqttv5.common.MqttException;
import org.eclipse.paho.mqttv5.common.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Squbi
 */
@Data
public class MqttTemplate {
    private static final Logger LOGGER = LoggerFactory.getLogger(MqttTemplate.class);

    private final MqttClientFactory factory;
    private final String clientId;
    private MqttClient client;
    private MqttCallback callback;
    private MqttInitializer initializer;

    public MqttTemplate(MqttClientFactory factory, String clientId, MqttMessageArrivedCall call, MqttInitializer initializer) throws MqttException {
        this.factory = factory;
        this.clientId = clientId;
        this.initializer = initializer;

        this.client = factory.connClient(clientId);
        this.callback = new MqttCallbackImpl(initializer,call, this.client);
        this.client.setCallback(this.callback);
    }

    public void publish(String topic, MqttMessage message) throws MqttException {
        this.client.publish(topic, message);
    }

    public void subscribe(String topic, int qos) throws MqttException {
        this.client.subscribe(topic, qos);
    }
}
